import { FastifyInstance } from 'fastify';
import { z } from 'zod';
import { v4 as uuidv4 } from 'uuid';
import {
  ApiResponseBuilder,
  MCPMessageSchema,
  PaginationSchema,
  ErrorCode,
  type MCPMessage,
} from '../types/index.js';
import { ServiceFactory } from '../../messaging/services/index.js';

const SendMessageRequestSchema = MCPMessageSchema.omit({
  id: true,
  timestamp: true,
  retryCount: true
}).extend({
  id: z.string().uuid({ message: "无效的UUID格式" }).optional()
});

const BatchMessageRequestSchema = z.object({
  messages: z.array(SendMessageRequestSchema).min(1).max(100)
});

const MessageQuerySchema = PaginationSchema.extend({
  type: z.string().optional(),
  source: z.string().optional(),
  priority: z.enum(['low', 'medium', 'high', 'critical']).optional(),
  status: z.enum(['pending', 'processing', 'completed', 'failed']).optional(),
  fromDate: z.string().datetime({ message: "无效的日期时间格式" }).optional(),
  toDate: z.string().datetime({ message: "无效的日期时间格式" }).optional()
});


/**
 * MCP消息处理路由
 */
export async function messageRoutes(fastify: FastifyInstance) {

  // 发送单个消息
  fastify.post<{
    Body: z.infer<typeof SendMessageRequestSchema>
  }>('/messages', async (request, reply) => {
    try {
      const messageData = SendMessageRequestSchema.parse(request.body);
      const messageId = messageData.id || uuidv4();

      const message: MCPMessage = {
        ...messageData,
        id: messageId,
        timestamp: new Date().toISOString(),
        retryCount: 0,
        headers: {
          'x-source-ip': request.ip,
          'x-user-agent': request.headers['user-agent'] || 'unknown',
          ...messageData.headers
        }
      };

      const validatedMessage = MCPMessageSchema.parse(message);
      const messageProcessingService = ServiceFactory.getMessageProcessingService();
      await messageProcessingService.processMessage(validatedMessage, {
        storeInDatabase: true,
        createSession: false,
        processAsync: false
      });

      const response = ApiResponseBuilder.success({
        messageId: validatedMessage.id,
        status: 'accepted',
        timestamp: validatedMessage.timestamp
      }, { requestId: request.id });

      return reply.status(202).send(response);

    } catch (error) {
      if (error instanceof z.ZodError) {
        const response = ApiResponseBuilder.error(
          ErrorCode.VALIDATION_ERROR,
          '请求体验证失败',
          { validationErrors: (error).issues },
          { requestId: request.id }
        );
        return reply.status(400).send(response);
      }

      request.log.error({ error }, '消息处理失败');
      const response = ApiResponseBuilder.error(
        ErrorCode.MESSAGE_PROCESSING_FAILED,
        '消息处理失败',
        { error: (error as Error).message },
        { requestId: request.id }
      );

      return reply.status(500).send(response);
    }
  });

  // 批量发送消息
  fastify.post<{
    Body: z.infer<typeof BatchMessageRequestSchema>
  }>('/messages/batch', async (request, reply) => {
    try {
      const { messages } = BatchMessageRequestSchema.parse(request.body);
      const results = [];
      let acceptedCount = 0;
      let rejectedCount = 0;

      for (const messageData of messages) {
        try {
          const messageId = messageData.id || uuidv4();

          const message: MCPMessage = {
            ...messageData,
            id: messageId,
            timestamp: new Date().toISOString(),
            retryCount: 0,
            headers: {
              'x-source-ip': request.ip,
              'x-user-agent': request.headers['user-agent'] || 'unknown',
              'x-batch-request': 'true',
              ...messageData.headers
            }
          };

          const validatedMessage = MCPMessageSchema.parse(message);
          const messageProcessingService = ServiceFactory.getMessageProcessingService();
          const processingResult = await messageProcessingService.processMessage(validatedMessage, {
            storeInDatabase: true,
            createSession: false,
            processAsync: true
          });

          results.push({
            messageId: validatedMessage.id,
            status: processingResult.status === 'processed' ? 'accepted' : 'rejected',
            ...(processingResult.error && { error: processingResult.error })
          });
          acceptedCount++;

        } catch (error) {
          results.push({
            messageId: messageData.id || 'unknown',
            status: 'rejected',
            error: error instanceof z.ZodError ?
              '消息格式无效' :
              (error as Error).message
          });
          rejectedCount++;
        }
      }

      const response = ApiResponseBuilder.success({
        accepted: acceptedCount,
        rejected: rejectedCount,
        messages: results
      }, { requestId: request.id });

      return reply.status(202).send(response);

    } catch (error) {
      if (error instanceof z.ZodError) {
        const response = ApiResponseBuilder.error(
          ErrorCode.VALIDATION_ERROR,
          '请求体验证失败',
          { validationErrors: (error).issues },
          { requestId: request.id }
        );
        return reply.status(400).send(response);
      }
      request.log.error({ error }, '批量消息处理失败');
      const response = ApiResponseBuilder.error(
        ErrorCode.MESSAGE_PROCESSING_FAILED,
        '批量消息处理失败',
        { error: (error as Error).message },
        { requestId: request.id }
      );

      return reply.status(500).send(response);
    }
  });

  // 查询消息列表
  fastify.get<{
    Querystring: z.infer<typeof MessageQuerySchema>
  }>('/messages', async (request, reply) => {
    try {
      const queryParams = MessageQuerySchema.parse(request.query);
      const mockMessages: MCPMessage[] = [];
      const mockTotal = 0;

      const response = ApiResponseBuilder.paginated(
        mockMessages,
        {
          page: queryParams.page,
          limit: queryParams.limit,
          total: mockTotal
        },
        { requestId: request.id }
      );

      return reply.send(response);

    } catch (error) {
      if (error instanceof z.ZodError) {
        const response = ApiResponseBuilder.error(
          ErrorCode.VALIDATION_ERROR,
          '查询参数验证失败',
          { validationErrors: (error).issues },
          { requestId: request.id }
        );
        return reply.status(400).send(response);
      }
      request.log.error({ error }, '查询消息列表失败');
      const response = ApiResponseBuilder.error(
        ErrorCode.DATABASE_ERROR,
        '查询消息列表失败',
        { error: (error as Error).message },
        { requestId: request.id }
      );

      return reply.status(500).send(response);
    }
  });

  // 获取单个消息详情
  fastify.get<{
    Params: { messageId: string }
  }>('/messages/:messageId', async (request, reply) => {
    try {
      const { messageId } = z.object({ messageId: z.string().uuid() }).parse(request.params);
      const message = null;

      if (!message) {
        const response = ApiResponseBuilder.error(
          ErrorCode.NOT_FOUND,
          `消息 ${messageId} 未找到`,
          undefined,
          { requestId: request.id }
        );
        return reply.status(404).send(response);
      }

      const response = ApiResponseBuilder.success(message, { requestId: request.id });
      return reply.send(response);

    } catch (error) {
      if (error instanceof z.ZodError) {
        const response = ApiResponseBuilder.error(
          ErrorCode.VALIDATION_ERROR,
          'URL参数验证失败',
          { validationErrors: (error).issues },
          { requestId: request.id }
        );
        return reply.status(400).send(response);
      }
      request.log.error({ error, messageId: request.params.messageId }, '获取消息详情失败');
      const response = ApiResponseBuilder.error(
        ErrorCode.DATABASE_ERROR,
        '获取消息详情失败',
        { error: (error as Error).message },
        { requestId: request.id }
      );

      return reply.status(500).send(response);
    }
  });
}
